<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"><title>NodeJS入门笔记 | InsectMk的个人空间</title><meta name="keywords" content="学习,NodeJS入门,NodeJS"><meta name="author" content="InsectMk,3067836615@qq.com"><meta name="copyright" content="InsectMk"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#f7f9fe"><meta name="mobile-web-app-capable" content="yes"><meta name="apple-touch-fullscreen" content="yes"><meta name="apple-mobile-web-app-title" content="NodeJS入门笔记"><meta name="application-name" content="NodeJS入门笔记"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="#f7f9fe"><meta property="og:type" content="article"><meta property="og:title" content="NodeJS入门笔记"><meta property="og:url" content="https://insectmk.top/posts/441e328e/index.html"><meta property="og:site_name" content="InsectMk的个人空间"><meta property="og:description" content="Bilibili黑马程序员NodeJS基于Bilibili黑马程序员NodeJS教程的学习记录 什么是nodejsnodejs是基于谷歌v8引擎的js解释器，nodejs包含npm，npm是node包管理工具 如何运行js代码12# 执行当前目录下名为xx.js的js源文件$ node xx.js"><meta property="og:locale" content="zh-CN"><meta property="og:image" content="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/nodejs/cover.png"><meta property="article:author" content="InsectMk"><meta property="article:tag" content="[&quot;InsectMk&quot;,&quot;个人博客&quot;]"><meta name="twitter:card" content="summary"><meta name="twitter:image" content="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/nodejs/cover.png"><meta name="description" content="Bilibili黑马程序员NodeJS基于Bilibili黑马程序员NodeJS教程的学习记录 什么是nodejsnodejs是基于谷歌v8引擎的js解释器，nodejs包含npm，npm是node包管理工具 如何运行js代码12# 执行当前目录下名为xx.js的js源文件$ node xx.js"><link rel="shortcut icon" href="/static/img/website/favicon.jpg"><link rel="canonical" href="https://insectmk.top/posts/441e328e/"><link rel="preconnect" href="//cdn.cbd.int"><link rel="preconnect" href="//busuanzi.ibruce.info"><meta name="google-site-verification" content="xxx"><meta name="baidu-site-verification" content="code-xxx"><meta name="msvalidate.01" content="xxx"><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.cbd.int/node-snackbar@0.1.16/dist/snackbar.min.css" media="print" onload='this.media="all"'><link rel="stylesheet" href="https://cdn.cbd.int/@fancyapps/ui@5.0.28/dist/fancybox/fancybox.css" media="print" onload='this.media="all"'><script>let GLOBAL_CONFIG={linkPageTop:{enable:!0,title:"与数百名博主无限进步",addFriendPlaceholder:"昵称（请勿包含博客等字样）：\n网站地址（要求博客地址，请勿提交个人主页）：\n头像图片url（请提供尽可能清晰的图片，我会上传到我自己的图床）：\n描述：\n站点截图（可选）：\n"},peoplecanvas:{enable:!0,img:"https://image.insectmk.cn/hexo-gitee-blog/article/_post/summary/hello-world/cover.jpg"},postHeadAiDescription:void 0,diytitle:void 0,LA51:void 0,greetingBox:void 0,twikooEnvId:"",commentBarrageConfig:void 0,root:"/",preloader:{source:3},friends_vue_info:void 0,navMusic:!0,mainTone:void 0,authorStatus:void 0,algolia:void 0,localSearch:{path:"/search.xml",preload:!0,languages:{hits_empty:"找不到您查询的内容：${query}"}},translate:{defaultEncoding:2,translateDelay:0,msgToTraditionalChinese:"繁",msgToSimplifiedChinese:"简",rightMenuMsgToTraditionalChinese:"转为繁体",rightMenuMsgToSimplifiedChinese:"转为简体"},noticeOutdate:void 0,highlight:{plugin:"highlight.js",highlightCopy:!0,highlightLang:!0,highlightHeightLimit:330},copy:{success:"复制成功",error:"复制错误",noSupport:"浏览器不支持"},relativeDate:{homepage:!1,simplehomepage:!0,post:!1},runtime:"天",date_suffix:{just:"刚刚",min:"分钟前",hour:"小时前",day:"天前",month:"个月前"},copyright:{copy:!0,copyrightEbable:!1,limitCount:50,languages:{author:"作者: InsectMk",link:"链接: ",source:"来源: InsectMk的个人空间",info:"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。",copySuccess:"复制成功，复制和转载请标注本文地址"}},lightbox:"fancybox",Snackbar:{chs_to_cht:"你已切换为繁体",cht_to_chs:"你已切换为简体",day_to_night:"你已切换为深色模式",night_to_day:"你已切换为浅色模式",bgLight:"#425AEF",bgDark:"#1f1f1f",position:"top-center"},source:{justifiedGallery:{js:"https://cdn.cbd.int/flickr-justified-gallery@2.1.2/dist/fjGallery.min.js",css:"https://cdn.cbd.int/flickr-justified-gallery@2.1.2/dist/fjGallery.css"}},isPhotoFigcaption:!1,islazyload:!1,isAnchor:!1,shortcutKey:void 0,autoDarkmode:!0}</script><script id="config-diff">var GLOBAL_CONFIG_SITE={configTitle:"InsectMk的个人空间",title:"NodeJS入门笔记",postAI:"",pageFillDescription:", 什么是nodejs, 如何运行js代码, 内置模块, 模块化, npm使用, express, 路由, 中间件, 中间件的分类, 跨域问题, 使用cors第三方中间件, mysql模块, Web开发模式, 在Express中使用Session认证, JWT跨域认证, 在Express中使用JWT黑马程序员基于黑马程序员教程的学习记录什么是是基于谷歌引擎的解释器包含是包管理工具如何运行代码执行当前目录下名为的源文件内置模块也和的一样有一些内置模块供我们使用文件模块引入模块路径模块引入模块服务模块引入模块模块化标准或者简洁使用因为默认下载包的地址在国外可以切换国内的镜像源下载镜像源快速切换工具查看镜像源列表使用列表中的镜像例下载某个包卸载某个包优秀的第三方模块能够快速开发中间件路由文件文件文件前缀端口中间件在收到请求时会先调用中间件中间件的调用会根据中间件注册的顺序执行而且会共用一个和也就是说可以在上游中间件给对象和对象加入一些属性或方法供下游中间件使用创建中间件你的代码你的代码注册全局生效中间件注册局部生效的中间件注册多个局部生效的中间件注意事项中间件的注册应当放在路由的前面中间件函数中的业务完成后应当调用函数否则请求会停止在此中间件中间件函数应当最后调用函数不能在函数调用后还继续写代码否则会造成代码混乱中间件的分类应用级别中间件注册在上的中间件直接注册在上注册在的路由上路由级别中间件注册在上的中间件错误级别中间件用于处理错误防止系统崩溃的中间件一定要在路由后注册定义错误中间件相较于普通中间件多了一个参数在路由后注册才会有对象否则为内置中间件自带的中间件内置中间件快速托管静态资源内置中间件解析请求体中的数据通过对象的属性获取内置中间件解析请求体中好像叫这个吧忘了的数据传入一个对象我也不太清楚什么意思通过对象的属性获取第三方中间件别人写的优秀的第三方中间件例如但是以后就自带了这个东西就是它是基于的封装首先要下载包使用方法与差不多传入一个对象我也不太清楚什么意思通过对象的属性获取跨域问题什么是跨域问题在浏览器控制台中会出现类似以下的报错协议域名端口号的不同导致的跨域问题解决方案主流的解决方案推荐使用有缺陷的解决方案只支持请求使用第三方中间件是解决跨域问题的第三方中间件下载第三方包在引入路由之前注册中间件在此写入路由指定域名通过跨域请求指定才能跨域访问指定所有域名都能跨域访问指定请求允许的请求方法指定允许所有的请求预检请求有些请求不是简单请求会先发送请求进行预检这个东西我也不太清楚说是要如果配置了就要配置在的前面然后前端会使用标签来解析响应的内容模块这也是第三方模块用于数据库的连接与操作下载第三方包导入模块并使用导入第三方包创建连接连接操作连接关闭连接使用带占位符的语句占位符使用多个占位符使用数据传数据男如果占位符太多可以使用对象查看受影响的行数如果只有一个占位符那么就可以不用使用数组传数据直接使用数据注意事项在执行操作的时候如果执行的语句是查询语句那么就是一个数组如果执行的是一个更新语句或者是删除语句那么就是一个对象其中的属性可以查看执行后的语句所影响的行数开发模式服务端渲染对友好但对服务器压力过大前后端分离服务器压力小不用渲染页面前端注重页面后端注重对不友好但能使用等框架提供的服务如何选择不同的场景使用不同的模式例如管理系统不怎么需要就可以使用前后端分离有些网站也采用首页使用服务端渲染其他页面使用前后端分离身份验证服务端渲染推荐使用认证机制使用它是存储在用户浏览器中一段不超过的字符串由一个名称一个值和其他几个用于控制有效期安全性和使用范围的可选属性组成每当发起请求会将未过期的一同发送到对应域名的服务器服务端可以通过响应头发送给客户端但是不安全因为谁都可以看会很好仿造所以使用认证因为中的数据是对应客户端的客户端只能访问属于自己的数据而不能访问别的客户端的数据前后端分离推荐使用认证机制在中使用认证下载中间件注册中间件属性的值可以为任意字符串固定写法固定写法往中存储数据取中的数据清空中的数据跨域认证由于默认不支持跨域如果使用作为身份验证机制配置会很麻烦是目前最流行的跨域认证解决方案工作流程首先客户端浏览器会发送登陆请求服务器接收到请求后先验证账号和密码验证通过后会将用户的信息对象经过加密后生成字符串服务端不会存储这个字符串然后响应给客户端客户端收到响应后会将存放在浏览器的或者中当客户端再次发送请求的时候会通过请求头的字段将发送给服务器服务器验证这个是否合法解析为之前打包所对应的数据然后针对数据发送对应的响应中不要携带密码信息组成部分三部分使用分隔头部有效荷载签名与只与安全有关防止破解是加密后的用户信息客户端如何使用推荐做法将放在请求同的字段中在中使用安装相关的包用于生成字符串用于将字符串解析还原成数据包安装如下两个相关的包定义密钥用于加密与解密建议命名为使用方法新版使用方法为接收变量名可任意更换定义密钥随意字符串配置解析中间件这个必须配置好像是配置加密算法配置解析配置哪些不使用解析添加中间件后会将解析的信息挂载在中解析请求体数据登陆成功参数加密信息必须为一个对象参数加密密钥参数配置有很多参数这里只配置了有效期为秒登陆成功登陆失败登陆失败请求此接口时应该在请求头的中添加信息为之前生成时需要打包的数据中的字段请求成功添加解析异常中间件处理无效的如果不是错误未知的错误",isPost:!0,isHome:!1,isHighlightShrink:!1,isToc:!0,postUpdate:"2022-11-08 12:43:11",postMainColor:""}</script><noscript><style type="text/css">#nav{opacity:1}.justified-gallery img{opacity:1}#post-meta time,#recent-posts time{display:inline!important}</style></noscript><script>(e=>{e.saveToLocal={set:(e,t,a)=>{var o;0!==a&&(o=Date.now(),localStorage.setItem(e,JSON.stringify({value:t,expiry:o+864e5*a})))},get:e=>{var t=localStorage.getItem(e);if(t){t=JSON.parse(t);if(!(Date.now()>t.expiry))return t.value;localStorage.removeItem(e)}}},e.getScript=(o,c={})=>new Promise((t,e)=>{let a=document.createElement("script");a.src=o,a.async=!0,a.onerror=e,a.onload=a.onreadystatechange=function(){var e=this.readyState;e&&"loaded"!==e&&"complete"!==e||(a.onload=a.onreadystatechange=null,t())},Object.keys(c).forEach(e=>{a.setAttribute(e,c[e])}),document.head.appendChild(a)}),e.getCSS=(o,c=!1)=>new Promise((t,e)=>{let a=document.createElement("link");a.rel="stylesheet",a.href=o,c&&(a.id=c),a.onerror=e,a.onload=a.onreadystatechange=function(){var e=this.readyState;e&&"loaded"!==e&&"complete"!==e||(a.onload=a.onreadystatechange=null,t())},document.head.appendChild(a)}),e.activateDarkMode=()=>{document.documentElement.setAttribute("data-theme","dark"),null!==document.querySelector('meta[name="theme-color"]')&&document.querySelector('meta[name="theme-color"]').setAttribute("content","#18171d")},e.activateLightMode=()=>{document.documentElement.setAttribute("data-theme","light"),null!==document.querySelector('meta[name="theme-color"]')&&document.querySelector('meta[name="theme-color"]').setAttribute("content","#f7f9fe")};var e=saveToLocal.get("theme"),t=window.matchMedia("(prefers-color-scheme: dark)").matches,a=window.matchMedia("(prefers-color-scheme: light)").matches,o=window.matchMedia("(prefers-color-scheme: no-preference)").matches,c=!t&&!a&&!o,t=(void 0===e?(a?activateLightMode():t?activateDarkMode():(o||c)&&((a=(new Date).getHours())<=6||18<=a?activateDarkMode:activateLightMode)(),window.matchMedia("(prefers-color-scheme: dark)").addListener(e=>{void 0===saveToLocal.get("theme")&&(e.matches?activateDarkMode:activateLightMode)()})):("light"===e?activateLightMode:activateDarkMode)(),saveToLocal.get("aside-status"));void 0!==t&&("hide"===t?document.documentElement.classList.add("hide-aside"):document.documentElement.classList.remove("hide-aside"));/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)&&document.documentElement.classList.add("apple")})(window)</script><meta name="generator" content="Hexo 7.3.0"><link rel="alternate" href="/atom.xml" title="InsectMk的个人空间" type="application/atom+xml"><link rel="alternate" href="/rss2.xml" title="InsectMk的个人空间" type="application/rss+xml"></head><body data-type="anzhiyu"><div id="web_bg"></div><div id="an_music_bg"></div><div id="loading-box" onclick="document.getElementById(&quot;loading-box&quot;).classList.add(&quot;loaded&quot;)"><div class="loading-bg"><img class="loading-img nolazyload" alt="加载头像" src="/static/img/head/insectmk.jpg"><div class="loading-image-dot"></div></div></div><script>let preloader={endLoading:()=>{document.getElementById("loading-box").classList.add("loaded")},initLoading:()=>{document.getElementById("loading-box").classList.remove("loaded")}};window.addEventListener("load",()=>{preloader.endLoading()}),setTimeout(function(){preloader.endLoading()},1e4),document.addEventListener("pjax:send",()=>{preloader.initLoading()}),document.addEventListener("pjax:complete",()=>{preloader.endLoading()})</script><link rel="stylesheet" href="https://cdn.cbd.int/anzhiyu-theme-static@1.1.10/progress_bar/progress_bar.css"><script async src="https://cdn.cbd.int/pace-js@1.2.4/pace.min.js" data-pace-options="{ &quot;restartOnRequestAfter&quot;:false,&quot;eventLag&quot;:false}"></script><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><div id="nav-group"><span id="blog_name"><div class="back-home-button"><i class="anzhiyufont anzhiyu-icon-grip-vertical"></i><div class="back-menu-list-groups"><div class="back-menu-list-group"><div class="back-menu-list-title">网页</div><div class="back-menu-list"><a class="back-menu-item" target="_blank" rel="noopener" href="https://insectmk.cn/" title="主博客"><img class="back-menu-item-icon" src="/static/img/website/favicon.jpg" alt="主博客"><span class="back-menu-item-text">主博客</span></a><a class="back-menu-item" href="https://insectmk.top/" title="次博客"><img class="back-menu-item-icon" src="/static/img/website/favicon.jpg" alt="次博客"><span class="back-menu-item-text">次博客</span></a></div></div><div class="back-menu-list-group"><div class="back-menu-list-title">项目</div><div class="back-menu-list"><a class="back-menu-item" target="_blank" rel="noopener" href="https://gitee.com/insectmk/chatbot-web" title="智能聊天机器人网站"><img class="back-menu-item-icon" src="https://image.insectmk.cn/hexo-gitee-blog/project/icon/chatbot-web.jpg" alt="智能聊天机器人网站"><span class="back-menu-item-text">智能聊天机器人网站</span></a></div></div></div></div><a id="site-name" href="/" accesskey="h"><div class="title">InsectMk的个人空间</div><i class="anzhiyufont anzhiyu-icon-house-chimney"></i></a></span><div class="mask-name-container"><div id="name-container"><a id="page-name" href="javascript:anzhiyu.scrollToDest(0, 500)">PAGE_NAME</a></div></div><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-home"></use></svg><span>主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-hand-peace"></use></svg><span>娱乐</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/entertainment/gallery/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-images"></use></svg><span>图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-comments"></use></svg><span>交流</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/contact/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-paper-plane"></use></svg><span>留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/contact/link/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-link"></use></svg><span>友链</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-compass"></use></svg><span>目录</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-archive"></use></svg><span>分类</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-tags"></use></svg><span>标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-folder-open"></use></svg><span>归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-server"></use></svg><span>服务</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/server/left4dead2/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-icons-left__dead_"></use></svg><span>求生之路</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/server/minecraft/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-minecraft"></use></svg><span>我的世界</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-clipboard"></use></svg><span>日志</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/log/website/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-website-with-different-sections"></use></svg><span>个人网站</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/log/pc/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-desktop"></use></svg><span>个人电脑</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-bars"></use></svg><span>其他</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/extend/remind/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-note"></use></svg><span>备忘</span></a></li></ul></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-id-card"></use></svg><span>关于</span></a></div></div></div><div id="nav-right"><div class="nav-button" id="randomPost_button"><a class="site-page" onclick="toRandomPost()" title="随机前往一个文章" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-dice"></i></a></div><div class="nav-button" id="search-button"><a class="site-page social-icon search" href="javascript:void(0);" title="搜索🔍" accesskey="s"><i class="anzhiyufont anzhiyu-icon-magnifying-glass"></i><span> 搜索</span></a></div><input id="center-console" type="checkbox"><label class="widget" for="center-console" title="中控台" onclick="anzhiyu.switchConsole()"><i class="left"></i><i class="widget center"></i><i class="widget right"></i></label><div id="console"><div class="console-card-group-reward"><ul class="reward-all console-card"><li class="reward-item"><a href="/static/img/website/reward/wechat.png" target="_blank"><img class="post-qr-code-img" alt="微信" src="/static/img/website/reward/wechat.png"></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/static/img/website/reward/alipay.png" target="_blank"><img class="post-qr-code-img" alt="支付宝" src="/static/img/website/reward/alipay.png"></a><div class="post-qr-code-desc">支付宝</div></li></ul></div><div class="console-card-group"><div class="console-card-group-left"><div class="console-card" id="card-newest-comments"><div class="card-content"><div class="author-content-item-tips">互动</div><span class="author-content-item-title">最新评论</span></div><div class="aside-list"><span>正在加载中...</span></div></div></div><div class="console-card-group-right"><div class="console-card tags"><div class="card-content"><div class="author-content-item-tips">兴趣点</div><span class="author-content-item-title">寻找你感兴趣的领域</span><div class="card-tags"><div class="item-headline"></div><div class="card-tag-cloud"><a href="/tags/AOP/" style="font-size:1.05rem">AOP<sup>1</sup></a><a href="/tags/Butterfly/" style="font-size:1.05rem">Butterfly<sup>4</sup></a><a href="/tags/Docker/" style="font-size:1.05rem">Docker<sup>6</sup></a><a href="/tags/ElementUI/" style="font-size:1.05rem">ElementUI<sup>1</sup></a><a href="/tags/Frp/" style="font-size:1.05rem">Frp<sup>1</sup></a><a href="/tags/Hexo/" style="font-size:1.05rem">Hexo<sup>8</sup></a><a href="/tags/IntelliJ-IDEA/" style="font-size:1.05rem">IntelliJ IDEA<sup>1</sup></a><a href="/tags/JDK/" style="font-size:1.05rem">JDK<sup>1</sup></a><a href="/tags/JWT/" style="font-size:1.05rem">JWT<sup>1</sup></a><a href="/tags/Java/" style="font-size:1.05rem">Java<sup>35</sup></a><a href="/tags/Junit/" style="font-size:1.05rem">Junit<sup>1</sup></a><a href="/tags/Leanote/" style="font-size:1.05rem">Leanote<sup>1</sup></a><a href="/tags/Maven/" style="font-size:1.05rem">Maven<sup>2</sup></a><a href="/tags/MyBatisPlus/" style="font-size:1.05rem">MyBatisPlus<sup>1</sup></a><a href="/tags/MySQL5-7/" style="font-size:1.05rem">MySQL5.7<sup>1</sup></a><a href="/tags/Mybatis/" style="font-size:1.05rem">Mybatis<sup>1</sup></a><a href="/tags/MybatisPlus/" style="font-size:1.05rem">MybatisPlus<sup>1</sup></a><a href="/tags/OSS/" style="font-size:1.05rem">OSS<sup>1</sup></a><a href="/tags/Spring/" style="font-size:1.05rem">Spring<sup>2</sup></a><a href="/tags/Spring-Boot/" style="font-size:1.05rem">SpringBoot<sup>6</sup></a><a href="/tags/Vue2/" style="font-size:1.05rem">Vue2<sup>9</sup></a><a href="/tags/Vue3/" style="font-size:1.05rem">Vue3<sup>1</sup></a><a href="/tags/Vuetify/" style="font-size:1.05rem">Vuetify<sup>1</sup></a><a href="/tags/Vuex/" style="font-size:1.05rem">Vuex<sup>1</sup></a><a href="/tags/Waline/" style="font-size:1.05rem">Waline<sup>3</sup></a><a href="/tags/mvc/" style="font-size:1.05rem">mvc<sup>3</sup></a><a href="/tags/mybatis/" style="font-size:1.05rem">mybatis<sup>1</sup></a><a href="/tags/profile/" style="font-size:1.05rem">profile<sup>1</sup></a><a href="/tags/spring/" style="font-size:1.05rem">spring<sup>5</sup></a><a href="/tags/springboot/" style="font-size:1.05rem">springboot<sup>4</sup></a><a href="/tags/transaction/" style="font-size:1.05rem">transaction<sup>1</sup></a><a href="/tags/yaml/" style="font-size:1.05rem">yaml<sup>2</sup></a><a href="/tags/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2/" style="font-size:1.05rem">个人博客<sup>11</sup></a><a href="/tags/%E4%BA%8B%E5%8A%A1/" style="font-size:1.05rem">事务<sup>1</sup></a><a href="/tags/%E5%88%86%E9%A1%B5/" style="font-size:1.05rem">分页<sup>1</sup></a><a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size:1.05rem">前端<sup>1</sup></a><a href="/tags/%E6%9C%8D%E5%8A%A1%E5%99%A8/" style="font-size:1.05rem">服务器<sup>20</sup></a><a href="/tags/%E6%AF%95%E4%B8%9A%E8%AE%BE%E8%AE%A1/" style="font-size:1.05rem">毕业设计<sup>14</sup></a><a href="/tags/%E7%A6%85%E9%81%93/" style="font-size:1.05rem">禅道<sup>1</sup></a><a href="/tags/%E7%BB%BF%E8%89%B2%E8%A7%A3%E5%8E%8B/" style="font-size:1.05rem">绿色解压<sup>1</sup></a></div></div><hr></div></div><div class="console-card history"><div class="item-headline"><i class="anzhiyufont anzhiyu-icon-box-archiv"></i><span>文章</span></div><div class="card-archives"><div class="item-headline"><i class="anzhiyufont anzhiyu-icon-archive"></i><span>归档</span><a class="card-more-btn" href="/archives/" title="查看更多"> <i class="anzhiyufont anzhiyu-icon-angle-right"></i></a></div><ul class="card-archive-list"><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/07/"><span class="card-archive-list-date">七月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">4</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/06/"><span class="card-archive-list-date">六月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">1</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/05/"><span class="card-archive-list-date">五月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">4</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/04/"><span class="card-archive-list-date">四月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">8</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/03/"><span class="card-archive-list-date">三月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">9</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/02/"><span class="card-archive-list-date">二月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">5</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2024/01/"><span class="card-archive-list-date">一月 2024</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">5</span><span>篇</span></div></a></li><li class="card-archive-list-item"><a class="card-archive-list-link" href="/archives/2023/10/"><span class="card-archive-list-date">十月 2023</span><div class="card-archive-list-count-group"><span class="card-archive-list-count">8</span><span>篇</span></div></a></li></ul></div><hr></div></div></div><div class="button-group"><div class="console-btn-item"><a class="darkmode_switchbutton" title="显示模式切换" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-moon"></i></a></div><div class="console-btn-item" id="consoleHideAside" onclick="anzhiyu.hideAsideBtn()" title="边栏显示控制"><a class="asideSwitch"><i class="anzhiyufont anzhiyu-icon-arrows-left-right"></i></a></div><div class="console-btn-item" id="consoleMusic" onclick="anzhiyu.musicToggle()" title="音乐开关"><a class="music-switch"><i class="anzhiyufont anzhiyu-icon-music"></i></a></div></div><div class="console-mask" onclick="anzhiyu.hideConsole()" href="javascript:void(0);"></div></div><div class="nav-button" id="nav-totop"><a class="totopbtn" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-arrow-up"></i><span id="percent" onclick="anzhiyu.scrollToDest(0,500)">0</span></a></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);" title="切换"><i class="anzhiyufont anzhiyu-icon-bars"></i></a></div></div></div></nav></header><main id="blog-container"><div class="layout" id="content-inner"><div id="post"><div id="post-info"><div id="post-firstinfo"><div class="meta-firstline"><a class="post-meta-original">原创</a><span class="post-meta-categories"><span class="post-meta-separator"></span><i class="anzhiyufont anzhiyu-icon-inbox post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%AC%94%E8%AE%B0/" itemprop="url">笔记</a></span><span class="article-meta tags"><a class="article-meta__tags" href="/tags/%E5%AD%A6%E4%B9%A0/" tabindex="-1" itemprop="url"> <span><i class="anzhiyufont anzhiyu-icon-hashtag"></i>学习</span></a><a class="article-meta__tags" href="/tags/NodeJS%E5%85%A5%E9%97%A8/" tabindex="-1" itemprop="url"> <span><i class="anzhiyufont anzhiyu-icon-hashtag"></i>NodeJS入门</span></a><a class="article-meta__tags" href="/tags/NodeJS/" tabindex="-1" itemprop="url"> <span><i class="anzhiyufont anzhiyu-icon-hashtag"></i>NodeJS</span></a></span></div></div><h1 class="post-title" itemprop="name headline">NodeJS入门笔记</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="anzhiyufont anzhiyu-icon-calendar-days post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" itemprop="dateCreated datePublished" datetime="2022-11-07T14:35:11.000Z" title="发表于 2022-11-07 22:35:11">2022-11-07</time><span class="post-meta-separator"></span><i class="anzhiyufont anzhiyu-icon-history post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" itemprop="dateCreated datePublished" datetime="2022-11-08T04:43:11.000Z" title="更新于 2022-11-08 12:43:11">2022-11-08</time></span></div><div class="meta-secondline"><span class="post-meta-separator"></span><span class="post-meta-wordcount"><i class="anzhiyufont anzhiyu-icon-file-word post-meta-icon" title="文章字数"></i><span class="post-meta-label" title="文章字数">字数总计:</span><span class="word-count" title="文章字数">3.2k</span><span class="post-meta-separator"></span><i class="anzhiyufont anzhiyu-icon-clock post-meta-icon" title="阅读时长"></i><span class="post-meta-label" title="阅读时长">阅读时长:</span><span>13分钟</span></span><span class="post-meta-separator"></span><span data-flag-title="NodeJS入门笔记"><i class="anzhiyufont anzhiyu-icon-fw-eye post-meta-icon"></i><span class="post-meta-label" title="阅读量">阅读量:</span><span class="waline-pageview-count" data-path="/posts/441e328e/" title="访问量"><i class="anzhiyufont anzhiyu-icon-spinner anzhiyu-spin"></i></span></span><span class="post-meta-separator"> </span><span class="post-meta-position" title="作者IP属地为成都"><i class="anzhiyufont anzhiyu-icon-location-dot"></i>成都</span><span class="post-meta-separator"></span><span class="post-meta-commentcount"><i class="anzhiyufont anzhiyu-icon-comments post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/posts/441e328e/#post-comment"><span class="waline-comment-count" data-path="/posts/441e328e/"><i class="anzhiyufont anzhiyu-icon-spinner anzhiyu-spin"></i></span></a></span></div></div></div><article class="post-content" id="article-container" itemscope itemtype="https://insectmk.top/posts/441e328e/"><header><a class="post-meta-categories" href="/categories/%E7%AC%94%E8%AE%B0/" itemprop="url">笔记</a><a href="/tags/%E5%AD%A6%E4%B9%A0/" tabindex="-1" itemprop="url">学习</a><a href="/tags/NodeJS%E5%85%A5%E9%97%A8/" tabindex="-1" itemprop="url">NodeJS入门</a><a href="/tags/NodeJS/" tabindex="-1" itemprop="url">NodeJS</a><h1 id="CrawlerTitle" itemprop="name headline">NodeJS入门笔记</h1><span itemprop="author" itemscope itemtype="http://schema.org/Person">InsectMk</span><time itemprop="dateCreated datePublished" datetime="2022-11-07T14:35:11.000Z" title="发表于 2022-11-07 22:35:11">2022-11-07</time><time itemprop="dateCreated datePublished" datetime="2022-11-08T04:43:11.000Z" title="更新于 2022-11-08 12:43:11">2022-11-08</time></header><h1 id="Bilibili黑马程序员NodeJS"><a href="#Bilibili黑马程序员NodeJS" class="headerlink" title="Bilibili黑马程序员NodeJS"></a><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1a34y167AZ">Bilibili黑马程序员NodeJS</a></h1><p>基于<a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1a34y167AZ">Bilibili黑马程序员NodeJS教程</a>的学习记录</p><h2 id="什么是nodejs"><a href="#什么是nodejs" class="headerlink" title="什么是nodejs"></a>什么是nodejs</h2><p>nodejs是基于谷歌v8引擎的js解释器，nodejs包含npm，npm是node包管理工具</p><h2 id="如何运行js代码"><a href="#如何运行js代码" class="headerlink" title="如何运行js代码"></a>如何运行js代码</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 执行当前目录下名为xx.js的js源文件</span></span><br><span class="line">$ node xx.js</span><br></pre></td></tr></table></figure><h2 id="内置模块"><a href="#内置模块" class="headerlink" title="内置模块"></a>内置模块</h2><p>nodejs也和chrome的v8一样，有一些内置模块供我们使用</p><ul><li><p>fs文件模块</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入fs模块</span></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br></pre></td></tr></table></figure></li><li><p>path路径模块</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入path模块</span></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br></pre></td></tr></table></figure></li><li><p>http服务模块</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入http模块</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br></pre></td></tr></table></figure></li></ul><h2 id="模块化"><a href="#模块化" class="headerlink" title="模块化"></a>模块化</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1、标准</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">xx</span> = xxx;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2、简洁</span></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">xx</span> = xxx;</span><br></pre></td></tr></table></figure><h2 id="npm使用"><a href="#npm使用" class="headerlink" title="npm使用"></a>npm使用</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 因为npm默认下载包的地址在国外，可以切换国内的镜像源</span></span><br><span class="line"><span class="comment"># 下载镜像源快速切换工具nrm</span></span><br><span class="line">$ npm install -g nrm</span><br><span class="line"></span><br><span class="line"><span class="comment"># 查看镜像源列表</span></span><br><span class="line">$ nrm <span class="built_in">ls</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用列表中的镜像，例：</span></span><br><span class="line">$ nrm use taobao</span><br><span class="line"></span><br><span class="line"><span class="comment"># 下载某个包</span></span><br><span class="line">$ npm install xxxx[@version] [--save]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 卸载某个包</span></span><br><span class="line">$ npm uninstall xxxx[@version] [--save]</span><br></pre></td></tr></table></figure><h2 id="express"><a href="#express" class="headerlink" title="express"></a>express</h2><p>优秀的第三方模块，能够快速开发中间件</p><h3 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 文件1</span></span><br><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Router</span> = express.<span class="title class_">Router</span>();</span><br><span class="line"><span class="title class_">Router</span>.<span class="title function_">get</span>(<span class="string">&#x27;path1&#x27;</span>,func1);</span><br><span class="line"><span class="title class_">Router</span>.<span class="title function_">post</span>(<span class="string">&#x27;path2&#x27;</span>,func2);</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="title class_">Router</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 文件2</span></span><br><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Router</span> = <span class="built_in">require</span>(<span class="string">&#x27;./文件1&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="string">&#x27;前缀&#x27;</span>,<span class="title class_">Router</span>);</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">listen</span>(端口,funciton;</span><br></pre></td></tr></table></figure><h3 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h3><p>express在收到请求时会先调用中间件</p><p>中间件的调用会根据中间件注册的顺序执行，而且会共用一个res和req，也就是说可以在上游中间件给res对象和req对象加入一些属性或方法供下游中间件使用。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建中间件</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">mw1</span>(<span class="params">req,res,next</span>) &#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    你的代码</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">	<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">mw2</span>(<span class="params">req,res,next</span>) &#123;</span><br><span class="line">	<span class="comment">/*</span></span><br><span class="line"><span class="comment">	你的代码</span></span><br><span class="line"><span class="comment">	*/</span></span><br><span class="line">	<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注册全局生效中间件</span></span><br><span class="line">app.<span class="title function_">use</span>(mw1);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注册局部生效的中间件</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,mw2,func);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注册多个局部生效的中间件</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,[mw1,mw2],func);</span><br><span class="line"><span class="comment">// or</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,mw1,mw2,func);</span><br></pre></td></tr></table></figure><p><strong>注意事项</strong></p><ul><li>中间件的注册应当放在路由的前面</li><li>中间件函数中的业务完成后应当调用next函数，否则请求会停止在此中间件</li><li>中间件函数应当最后调用next函数，不能在next函数调用后还继续写代码，否则会造成代码混乱</li></ul><h3 id="中间件的分类"><a href="#中间件的分类" class="headerlink" title="中间件的分类"></a>中间件的分类</h3><ul><li><p>应用级别中间件<br>注册在app上的中间件</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">mw</span> = (<span class="params">req,res,next</span>) =&gt; &#123;</span><br><span class="line">	<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 直接注册在app上</span></span><br><span class="line">app.<span class="title function_">use</span>(mw);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注册在app的路由上</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,mw,func);</span><br></pre></td></tr></table></figure></li><li><p>路由级别中间件</p></li></ul><p>注册在Router上的中间件</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Router</span> = express.<span class="title class_">Router</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">mw</span> = (<span class="params">req,res,next</span>) =&gt; &#123;</span><br><span class="line">	<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title class_">Router</span>.<span class="title function_">use</span>(mw);</span><br></pre></td></tr></table></figure><ul><li>错误级别中间件</li></ul><p>用于处理错误，防止系统崩溃的中间件，一定要在路由后注册</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义错误中间件，相较于普通中间件多了一个err参数</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">mw</span> = (<span class="params">err,req,res,next</span>) =&gt; &#123;</span><br><span class="line">	<span class="title function_">next</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,func);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在路由后注册才会有err对象，否则err为undefined</span></span><br><span class="line">app.<span class="title function_">use</span>(mw);</span><br></pre></td></tr></table></figure><ul><li>内置中间件</li></ul><p>express自带的中间件</p><ul><li>内置中间件-express.static()</li></ul><p>快速托管静态资源</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="string">&#x27;prefix&#x27;</span>,express.<span class="title function_">static</span>(<span class="string">&#x27;path&#x27;</span>));</span><br></pre></td></tr></table></figure><ul><li>内置中间件-express.json()</li></ul><p>解析请求体中的json数据</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(express.<span class="title function_">json</span>());</span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过req对象的body属性获取</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,<span class="function">(<span class="params">req,res</span>) =&gt;</span> &#123;</span><br><span class="line">	<span class="keyword">let</span> body = req.<span class="property">body</span>;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(body);</span><br><span class="line">	res.<span class="title function_">send</span>(body);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><ul><li>内置中间件-express.urlencoded()</li></ul><p>解析请求体中url-www-extended（好像叫这个吧，忘了）的数据</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 传入一个对象（我也不太清楚什么意思）</span></span><br><span class="line">app.<span class="title function_">use</span>(express.<span class="title function_">urlencoded</span>(&#123;</span><br><span class="line">	<span class="attr">extended</span>: <span class="literal">false</span>;</span><br><span class="line">&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过req对象的body属性获取</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,<span class="function">(<span class="params">req,res</span>) =&gt;</span> &#123;</span><br><span class="line">	<span class="keyword">let</span> body = req.<span class="property">body</span>;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(body);</span><br><span class="line">	res.<span class="title function_">send</span>(body);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><ul><li>第三方中间件</li></ul><p>别人写的优秀的第三方中间件，例如body-parser，但是<a href="mailto:&#x65;&#120;&#x70;&#114;&#101;&#115;&#115;&#64;&#x34;&#46;&#x31;&#x36;&#46;&#48;">&#x65;&#120;&#x70;&#114;&#101;&#115;&#115;&#64;&#x34;&#46;&#x31;&#x36;&#46;&#48;</a>以后就自带了这个东西<br>就是express.urlencoded()，它是基于body-parser的封装<br>首先要下载body-parser包</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install body-parser --save</span><br></pre></td></tr></table></figure><p>使用方法与express.encoded()差不多</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> bodyParser = <span class="built_in">require</span>(<span class="string">&#x27;body-parser&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 传入一个对象（我也不太清楚什么意思）</span></span><br><span class="line">app.<span class="title function_">use</span>(bodyParser.<span class="title function_">urlencoded</span>(&#123;</span><br><span class="line">	<span class="attr">extended</span>: <span class="literal">false</span>;</span><br><span class="line">&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 通过req对象的body属性获取</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;path&#x27;</span>,<span class="function">(<span class="params">req,res</span>) =&gt;</span> &#123;</span><br><span class="line">	<span class="keyword">let</span> body = req.<span class="property">body</span>;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(body);</span><br><span class="line">	res.<span class="title function_">send</span>(body);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><h2 id="跨域问题"><a href="#跨域问题" class="headerlink" title="跨域问题"></a>跨域问题</h2><p><strong>什么是跨域问题</strong></p><p>在浏览器控制台中会出现类似以下的报错</p><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Access to XMLHttpRequest at &#x27;http://127.0.0.1/api/get?id=2206831544&amp;name=%E9%A9%AC%E6%9F%90&amp;gender=%E7%94%B7&#x27; from origin &#x27;null&#x27; has been blocked by CORS policy: No &#x27;Access-Control-Allow-Origin&#x27; header is present on the requested resource.</span><br></pre></td></tr></table></figure><p>协议、域名、端口号的不同导致的跨域问题</p><p><strong>解决方案</strong></p><p>CORS（主流的解决方案，推荐使用）<br>JSONP（有缺陷的解决方案，只支持get请求）</p><h3 id="使用cors第三方中间件"><a href="#使用cors第三方中间件" class="headerlink" title="使用cors第三方中间件"></a>使用cors第三方中间件</h3><p>cors是express解决跨域问题的第三方中间件</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 下载cors第三方包</span></span><br><span class="line">$ npm install cors --save</span><br></pre></td></tr></table></figure><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> cors = <span class="built_in">require</span>(<span class="string">&#x27;cors&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在引入路由之前注册cors中间件</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">cors</span>());</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在此写入路由</span></span><br></pre></td></tr></table></figure><p><strong>指定域名通过跨域请求</strong></p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 指定http://19maken.top才能跨域访问</span></span><br><span class="line">res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>,<span class="string">&#x27;http://19maken.top&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定所有域名都能跨域访问</span></span><br><span class="line">res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>,<span class="string">&#x27;*&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定请求允许的请求方法</span></span><br><span class="line">res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Methods&#x27;</span>,<span class="string">&#x27;POST,GET,DELETE,HEAD&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 指定允许所有的请求</span></span><br><span class="line">res.<span class="title function_">setHeader</span>(<span class="string">&#x27;Access-Control-Allow-Methods&#x27;</span>,<span class="string">&#x27;*&#x27;</span>);</span><br></pre></td></tr></table></figure><p>预检请求<br>有些请求不是简单请求，会先发送OPTION请求进行预检</p><p><strong>jsonp</strong></p><p>这个东西我也不太清楚，说是要如果配置了cors，就要配置在cors的前面，然后前端会使用script标签来解析响应的内容。</p><h2 id="mysql模块"><a href="#mysql模块" class="headerlink" title="mysql模块"></a>mysql模块</h2><p>这也是第三方模块，用于数据库的连接与操作。</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 下载第三方包</span></span><br><span class="line">$ npm install mysql</span><br></pre></td></tr></table></figure><p>导入mysql模块并使用</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入mysql第三方包</span></span><br><span class="line"><span class="keyword">const</span> mysql = <span class="built_in">require</span>(<span class="string">&#x27;mysql&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建连接</span></span><br><span class="line"><span class="keyword">const</span> connection = mysql.<span class="title function_">createConnection</span>(&#123;</span><br><span class="line">	<span class="attr">host</span>: <span class="string">&#x27;localhost&#x27;</span>,</span><br><span class="line">	<span class="attr">user</span>: <span class="string">&#x27;user&#x27;</span>,</span><br><span class="line">	<span class="attr">password</span>: <span class="string">&#x27;secret&#x27;</span>,</span><br><span class="line">	<span class="attr">database</span>: <span class="string">&#x27;database&#x27;</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 连接</span></span><br><span class="line">connection.<span class="title function_">connect</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 操作连接</span></span><br><span class="line"><span class="keyword">const</span> sql = <span class="string">&#x27;SELECT 1+1 AS solution&#x27;</span>;</span><br><span class="line">connection.<span class="title function_">query</span>(sql,<span class="keyword">function</span>(<span class="params">error,results,fields</span>) &#123;</span><br><span class="line">	<span class="keyword">if</span> (error) <span class="keyword">throw</span> error;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;The solution is:&#x27;</span>, results[<span class="number">0</span>],solution);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 关闭连接</span></span><br><span class="line">connection.<span class="title function_">end</span>();</span><br></pre></td></tr></table></figure><p>使用带占位符的sql语句，PS：占位符使用?</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1、多个占位符，使用数据传数据</span></span><br><span class="line"><span class="keyword">const</span> sql = <span class="string">&#x27;SELECT * FROM table WHERE age &gt; ? and gender = ?&#x27;</span>;</span><br><span class="line">connection.<span class="title function_">query</span>(sql,[<span class="number">18</span>,<span class="string">&#x27;男&#x27;</span>],<span class="keyword">function</span>(<span class="params">error,results,fields</span>) &#123;</span><br><span class="line">	<span class="keyword">if</span> (error) <span class="keyword">throw</span> error;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(results);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2、如果占位符太多，可以使用对象</span></span><br><span class="line"><span class="keyword">const</span> sql = <span class="string">&#x27;INSERT INTO table (fields) values (?)&#x27;</span>;</span><br><span class="line"><span class="keyword">const</span> data = &#123;</span><br><span class="line">	<span class="attr">field1</span>: field1,</span><br><span class="line">	<span class="attr">field2</span>: field2,</span><br><span class="line">	...</span><br><span class="line">&#125;</span><br><span class="line">connection.<span class="title function_">query</span>(sql,data,<span class="keyword">function</span>(<span class="params">error,results,fields</span>) &#123;</span><br><span class="line">	<span class="keyword">if</span> (error) <span class="keyword">throw</span> error;</span><br><span class="line">	<span class="comment">// 查看受影响的行数</span></span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(results.<span class="property">affectedRows</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3、如果只有一个占位符，那么就可以不用使用数组传数据，直接使用数据</span></span><br><span class="line"><span class="keyword">const</span> sql = <span class="string">&#x27;SELECT * FROM table WHERE age &gt; ?&#x27;</span>;</span><br><span class="line">connection.<span class="title function_">query</span>(sql,<span class="number">18</span>,<span class="keyword">function</span>(<span class="params">error,results,fields</span>) &#123;</span><br><span class="line">	<span class="keyword">if</span> (error) <span class="keyword">throw</span> error;</span><br><span class="line">	<span class="variable language_">console</span>.<span class="title function_">log</span>(results);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><p><strong>注意事项</strong></p><p>在执行操作的时候，如果执行的语句是查询语句，那么results就是一个数组，如果执行的是一个更新语句或者是删除语句，那么results就是一个对象，其中results的affectedRows属性可以查看执行后的语句所影响的行数。</p><h2 id="Web开发模式"><a href="#Web开发模式" class="headerlink" title="Web开发模式"></a>Web开发模式</h2><p>SEO?</p><p>服务端渲染</p><p>对SEO友好，但对服务器压力过大</p><p>前后端分离</p><p>服务器压力小，不用渲染页面，前端注重页面，后端注重API，对SEO不友好，但能使用VUE等框架提供的服务</p><p>如何选择？</p><p>不同的场景使用不同的模式，例如管理系统不怎么需要SEO，就可以使用前后端分离。有些网站也采用首页使用服务端渲染，其他页面使用前后端分离。</p><p><strong>身份验证</strong></p><ul><li>服务端渲染推荐使用Session认证机制。</li></ul><p>使用Cookie，它是存储在用户浏览器中一段不超过4KB的字符串，由一个名称（name）、一个值（value）和其他几个用于控制Cookie有效期、安全性和使用范围的可选属性组成。每当发起请求，会将未过期的Cookie一同发送到对应域名的服务器。服务端可以通过响应头发送Cookie给客户端。但是Cookie不安全，因为谁都可以看，会很好仿造。所以使用Cookie+Session认证。<strong>因为Session中的数据是对应客户端的</strong>客户端只能访问属于自己的session数据，而不能访问别的客户端的session数据。</p><ul><li>前后端分离推荐使用JWT认证机制。</li></ul><h2 id="在Express中使用Session认证"><a href="#在Express中使用Session认证" class="headerlink" title="在Express中使用Session认证"></a>在Express中使用Session认证</h2><p>下载express-session中间件</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ npm install express-session</span><br></pre></td></tr></table></figure><p>注册express-session中间件</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> session = <span class="built_in">require</span>(<span class="string">&#x27;express-session&#x27;</span>);</span><br><span class="line"><span class="keyword">var</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">session</span>(&#123;</span><br><span class="line">	<span class="attr">secret</span>: <span class="string">&#x27;keyboard cat&#x27;</span>,		<span class="comment">// secret属性的值可以为任意字符串</span></span><br><span class="line">	<span class="attr">resave</span>: <span class="literal">false</span>,				<span class="comment">// 固定写法</span></span><br><span class="line">	<span class="attr">saveUninitialized</span>: <span class="literal">true</span>		<span class="comment">// 固定写法</span></span><br><span class="line">&#125;));</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;/user/login&#x27;</span>,<span class="keyword">function</span>(<span class="params">req,res</span>) &#123;</span><br><span class="line">	<span class="comment">// 往session中存储数据</span></span><br><span class="line">	req.<span class="property">session</span>.<span class="property">xxx1</span> = xxx1;</span><br><span class="line">	req.<span class="property">session</span>.<span class="property">xxx2</span> = xxx2;</span><br><span class="line">	res.<span class="title function_">send</span>(<span class="string">&#x27;success&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;/user/getXxx&#x27;</span>,<span class="keyword">function</span>(<span class="params">req,res</span>) &#123;</span><br><span class="line">	<span class="comment">// 取session中的数据</span></span><br><span class="line">	res.<span class="title function_">send</span>(req.<span class="property">session</span>.<span class="property">xxx1</span> + <span class="string">&#x27;\n&#x27;</span> + req.<span class="property">session</span>.<span class="property">xxx2</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;/user/logout&#x27;</span>,<span class="keyword">function</span>(<span class="params">req,res</span>) &#123;</span><br><span class="line">	<span class="comment">// 清空Session中的数据</span></span><br><span class="line">	req.<span class="property">session</span>.<span class="title function_">destroy</span>();</span><br><span class="line">	res.<span class="title function_">send</span>(<span class="string">&#x27;success&#x27;</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure><h2 id="JWT跨域认证"><a href="#JWT跨域认证" class="headerlink" title="JWT跨域认证"></a>JWT跨域认证</h2><p>由于Cookie默认不支持跨域，如果使用Session+Cookie作为身份验证机制，配置会很麻烦。JWT（JSON Web Token）是目前最流行的跨域认证解决方案。</p><p><strong>JWT工作流程</strong></p><p>首先客户端（浏览器）会发送登陆请求，服务器接收到请求后先验证账号和密码，验证通过后会将用户的信息对象经过加密后生成Token字符串（服务端不会存储这个字符串），然后响应给客户端，客户端收到响应后会将Token存放在浏览器的LocalStorage或者SessionStorage中，当客户端再次发送请求的时候会通过请求头的Authorization字段将Token发送给服务器，服务器验证这个Token是否合法，解析为之前打包所对应的数据，然后针对数据发送对应的响应。<strong>JWT中不要携带密码信息</strong></p><p>JWT组成部分，三部分，使用“.”分隔</p><p>Header(头部).Payload(有效荷载).Signature(签名)</p><p>Header与Signature只与安全有关，防止破解。Payload是加密后的用户信息。</p><p><strong>客户端如何使用JWT？</strong></p><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 推荐做法：将JWT放在HTTP请求同的Authorization字段中。</span><br><span class="line">Authorization: Bearer &lt;token&gt;</span><br></pre></td></tr></table></figure><h2 id="在Express中使用JWT"><a href="#在Express中使用JWT" class="headerlink" title="在Express中使用JWT"></a>在Express中使用JWT</h2><p>安装JWT相关的包</p><p>jsonwebtoken 用于生成JWT字符串</p><p>express-jwt 用于将JWT字符串解析还原成JSON数据包</p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 安装如下两个JWT相关的包</span></span><br><span class="line">$ npm install jsonwebtoken express-jwt</span><br></pre></td></tr></table></figure><p>定义secret密钥：用于JWT加密与解密，建议命名为secretKey</p><p>使用方法</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> express = <span class="built_in">require</span>(<span class="string">&#x27;express&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> jwt = <span class="built_in">require</span>(<span class="string">&#x27;jsonwebtoken&#x27;</span>);</span><br><span class="line"><span class="comment">// 新版使用方法(7.7.7)，expressJWT为接收变量名，可任意更换</span></span><br><span class="line"><span class="keyword">var</span> &#123;<span class="attr">expressjwt</span>: expressJWT&#125; = <span class="built_in">require</span>(<span class="string">&#x27;express-jwt&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="title function_">express</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 定义secret密钥（随意字符串）</span></span><br><span class="line"><span class="keyword">const</span> secretKey = <span class="string">&#x27;XXXX xxxx II&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 配置JWT解析中间件</span></span><br><span class="line">	<span class="comment">// 这个algorithms必须配置，好像是配置加密算法</span></span><br><span class="line"><span class="comment">// expressJWT(&#123;&#125;)：配置解析</span></span><br><span class="line"><span class="comment">// expressJWT(&#123;&#125;).unless(&#123;&#125;)：配置哪些不使用解析</span></span><br><span class="line"><span class="comment">// 添加expressJWT中间件后，express会将解析的token信息挂载在req.user中</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">expressJWT</span>(&#123;</span><br><span class="line">	<span class="attr">secret</span>: secretKey,</span><br><span class="line">	<span class="attr">algorithms</span>: [<span class="string">&quot;HS256&quot;</span>]</span><br><span class="line">&#125;).<span class="title function_">unless</span>(&#123;</span><br><span class="line">	<span class="attr">path</span>: [<span class="regexp">/^\/api\//</span>]</span><br><span class="line">&#125;));</span><br><span class="line"><span class="comment">// 解析请求体JSON数据</span></span><br><span class="line">app.<span class="title function_">use</span>(express.<span class="title function_">json</span>());</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">post</span>(<span class="string">&#x27;/api/user/login/action&#x27;</span>,<span class="keyword">function</span>(<span class="params">req,res</span>) &#123;</span><br><span class="line">	<span class="keyword">const</span> user = req.<span class="property">body</span>;</span><br><span class="line">	<span class="keyword">if</span> (user.<span class="property">name</span> === <span class="string">&#x27;admin&#x27;</span> &amp;&amp; user.<span class="property">pwd</span> === <span class="string">&#x27;123456&#x27;</span>) &#123;</span><br><span class="line">		<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;登陆成功！&#x27;</span>);</span><br><span class="line">		<span class="comment">// 参数1：加密信息，必须为一个对象！</span></span><br><span class="line">		<span class="comment">// 参数2：加密密钥</span></span><br><span class="line">		<span class="comment">// 参数3：配置，有很多参数，这里只配置了token有效期为30秒</span></span><br><span class="line">		<span class="keyword">const</span> tokenStr = jwt.<span class="title function_">sign</span>(&#123;<span class="attr">username</span>: user.<span class="property">name</span>&#125;,secretKey,&#123;<span class="attr">expiresIn</span>: <span class="string">&#x27;30s&#x27;</span>&#125;);</span><br><span class="line"></span><br><span class="line">		res.<span class="title function_">send</span>(&#123;</span><br><span class="line">			<span class="attr">status</span>: <span class="number">200</span>,</span><br><span class="line">			<span class="attr">message</span>: <span class="string">&#x27;登陆成功！&#x27;</span>,</span><br><span class="line">			<span class="attr">token</span>: tokenStr</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;登陆失败！&#x27;</span>);</span><br><span class="line">		res.<span class="title function_">send</span>(&#123;</span><br><span class="line">			<span class="attr">status</span>: <span class="number">200</span>,</span><br><span class="line">			<span class="attr">message</span>: <span class="string">&#x27;登陆失败！&#x27;</span>,</span><br><span class="line">			<span class="attr">token</span>: <span class="literal">null</span></span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 请求此接口时应该在请求头的Authorization中添加token信息</span></span><br><span class="line">app.<span class="title function_">get</span>(<span class="string">&#x27;/user/info&#x27;</span>,<span class="keyword">function</span>(<span class="params">req,res</span>) &#123;</span><br><span class="line">	<span class="keyword">const</span> user = req.<span class="property">user</span>;</span><br><span class="line">	<span class="comment">// username为之前生成token时需要打包的数据中的字段</span></span><br><span class="line">	<span class="keyword">if</span> (user.<span class="property">username</span> === admin) &#123;</span><br><span class="line">		res.<span class="title function_">send</span>(&#123;</span><br><span class="line">			<span class="attr">code</span>: <span class="number">200</span>,</span><br><span class="line">			<span class="attr">msg</span>: <span class="string">&#x27;请求成功！&#x27;</span>,</span><br><span class="line">			<span class="attr">data</span>: &#123;</span><br><span class="line">				<span class="attr">name</span>: <span class="string">&#x27;admin&#x27;</span>,</span><br><span class="line">				<span class="attr">age</span>: <span class="number">19</span></span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加token解析异常中间件处理</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="function">(<span class="params">err,req,res,next</span>) =&gt;</span> &#123;</span><br><span class="line">	<span class="keyword">if</span> (err.<span class="property">name</span> === <span class="string">&#x27;UnauthorizedError&#x27;</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> res.<span class="title function_">send</span>(&#123;</span><br><span class="line">			<span class="attr">code</span>: <span class="number">401</span>,</span><br><span class="line">			<span class="attr">msg</span>: <span class="string">&#x27;无效的token&#x27;</span>,</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125; </span><br><span class="line"></span><br><span class="line">	<span class="comment">// 如果不是token错误</span></span><br><span class="line">	res.<span class="title function_">send</span>(&#123;</span><br><span class="line">		<span class="attr">code</span>: <span class="number">500</span>,</span><br><span class="line">		<span class="attr">msg</span>: <span class="string">&#x27;未知的错误&#x27;</span>,</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="copyright-cc-box"><i class="anzhiyufont anzhiyu-icon-copyright"></i></div><div class="post-copyright__author_box"><a class="post-copyright__author_img" target="_blank" rel="noopener" href="https://insectmk.cn" title="头像"><img class="post-copyright__author_img_back" src="/static/img/head/insectmk.jpg" title="头像" alt="头像"><img class="post-copyright__author_img_front" src="/static/img/head/insectmk.jpg" title="头像" alt="头像"></a><div class="post-copyright__author_name">InsectMk</div><div class="post-copyright__author_desc">今天特别开心！</div></div><div class="post-copyright__post__info"><a class="post-copyright__original" title="该文章为原创文章，注意版权协议" href="https://insectmk.top/posts/441e328e/">原创</a><a class="post-copyright-title"><span onclick='rm.copyPageUrl("https://insectmk.top/posts/441e328e/")'>NodeJS入门笔记</span></a></div><div class="post-tools" id="post-tools"><div class="post-tools-left"><div class="rewardLeftButton"></div><div class="shareRight"><div class="share-link mobile"><div class="share-qrcode"><div class="share-button" title="使用手机访问这篇文章"><i class="anzhiyufont anzhiyu-icon-qrcode"></i></div><div class="share-main"><div class="share-main-all"><div id="qrcode" title="https://insectmk.top/posts/441e328e/"></div><div class="reward-dec">使用手机访问这篇文章</div></div></div></div></div><div class="share-link weibo"><a class="share-button" target="_blank" href="https://service.weibo.com/share/share.php?title=undefined&amp;url=https://insectmk.top/posts/441e328e/&amp;pic=undefined" rel="external nofollow noreferrer noopener"><i class="anzhiyufont anzhiyu-icon-weibo"></i></a></div><script>function copyCurrentPageUrl(){var e=window.location.href,t=document.createElement("input");t.setAttribute("value",e),document.body.appendChild(t),t.select(),t.setSelectionRange(0,99999),document.execCommand("copy"),document.body.removeChild(t)}</script><div class="share-link copyurl"><div class="share-button" id="post-share-url" title="复制链接" onclick="copyCurrentPageUrl()"><i class="anzhiyufont anzhiyu-icon-link"></i></div></div></div></div></div><div class="post-copyright__notice"><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://insectmk.top" target="_blank">InsectMk的个人空间</a>！</span></div></div><div class="post-tools-right"><div class="tag_share"><div class="post-meta__box"><div class="post-meta__box__tag-list"><a class="post-meta__box__tags" href="/tags/%E5%AD%A6%E4%B9%A0/"><span class="tags-punctuation"><i class="anzhiyufont anzhiyu-icon-tag"></i></span>学习<span class="tagsPageCount">8</span></a><a class="post-meta__box__tags" href="/tags/NodeJS%E5%85%A5%E9%97%A8/"><span class="tags-punctuation"> <i class="anzhiyufont anzhiyu-icon-tag"></i></span>NodeJS入门<span class="tagsPageCount">1</span></a><a class="post-meta__box__tags" href="/tags/NodeJS/"><span class="tags-punctuation"> <i class="anzhiyufont anzhiyu-icon-tag"></i></span>NodeJS<span class="tagsPageCount">1</span></a></div></div></div><div class="post_share"><div class="social-share" data-image="https://image.insectmk.cn/hexo-gitee-blog/cover/github-insectmk.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.cbd.int/butterfly-extsrc@1.1.3/sharejs/dist/css/share.min.css" media="print" onload='this.media="all"'><script src="https://cdn.cbd.int/butterfly-extsrc@1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/9b7de2ae/"><img class="prev-cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/summary/hello-world/cover.jpg" onerror='onerror=null,src="/static/img/website/404.jpg"' alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Hexo建站感言</div></div></a></div><div class="next-post pull-right"><a href="/posts/62df11c0/"><img class="next-cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/vue2/cover.png" onerror='onerror=null,src="/static/img/website/404.jpg"' alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Vue2入门笔记（1）</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="anzhiyufont anzhiyu-icon-thumbs-up fa-fw" style="font-size:1.5rem;margin-right:4px"></i><span>喜欢这篇文章的人也看了</span></div><div class="relatedPosts-list"><div><a href="/posts/e5124b35/" title="Maven入门笔记（1）"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/maven-1/cover.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2022-11-28</div><div class="title">Maven入门笔记（1）</div></div></a></div><div><a href="/posts/3c2a06ae/" title="SpringBoot2学习笔记（1）基础篇"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/springboot2-1/cover.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2022-11-25</div><div class="title">SpringBoot2学习笔记（1）基础篇</div></div></a></div><div><a href="/posts/a560e78/" title="Redis学习笔记（一）"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/cover/redis.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2024-05-04</div><div class="title">Redis学习笔记（一）</div></div></a></div><div><a href="/posts/706abe2e/" title="Vue2入门笔记（2）"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/vue2-2/cover.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2022-11-25</div><div class="title">Vue2入门笔记（2）</div></div></a></div><div><a href="/posts/c8d6d94b/" title="Vue2入门笔记（3）"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/vue2-3/cover.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2022-11-27</div><div class="title">Vue2入门笔记（3）</div></div></a></div><div><a href="/posts/5501e1f2/" title="Vue2入门笔记（4）"><img class="cover" src="https://image.insectmk.cn/hexo-gitee-blog/article/_post/notes/vue2-4/cover.png" alt="cover"><div class="content is-center"><div class="date"><i class="anzhiyufont anzhiyu-icon-calendar-days fa-fw"></i> 2022-11-27</div><div class="title">Vue2入门笔记（4）</div></div></a></div></div></div><hr><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="anzhiyufont anzhiyu-icon-comments"></i><span> 评论</span></div><div class="comment-randomInfo"><a onclick="anzhiyu.addRandomCommentInfo()" href="javascript:void(0)">匿名评论</a><a href="/privacy" style="margin-left:4px">隐私政策</a></div></div><div class="comment-wrap"><div><div id="waline-wrap"></div></div></div></div><div class="comment-barrage"></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-content"><div class="author-info-avatar"><img class="avatar-img" src="/static/img/head/insectmk.jpg" onerror='this.onerror=null,this.src="/static/img/website/friend_404.gif"' alt="avatar"></div><div class="author-info__description"><div style="line-height:1.38;margin:.6rem 0;text-align:justify;color:rgba(255,255,255,.8)">这有关于<b style="color:#fff">程序开发、部署</b>相关的问题和看法，还有<b style="color:#fff">软件推荐</b>和<b style="color:#fff">分享</b>。</div><div style="line-height:1.38;margin:.6rem 0;text-align:justify;color:rgba(255,255,255,.8)">相信你可以在这里找到对你有用的<b style="color:#fff">知识</b>和<b style="color:#fff">教程</b>。</div></div><div class="author-info__bottom-group"><a class="author-info__bottom-group-left" href="/"><h1 class="author-info__name">InsectMk</h1><div class="author-info__desc">今天特别开心！</div></a><div class="card-info-social-icons is-center"><a class="social-icon faa-parent animated-hover" href="https://gitee.com/insectmk" target="_blank" title="Gitee"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-gitee"></use></svg></a><a class="social-icon faa-parent animated-hover" href="/static/img/website/contact/qq.png" target="_blank" title="QQ"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-qq"></use></svg></a><a class="social-icon faa-parent animated-hover" href="/static/img/website/contact/wechat.png" target="_blank" title="WeChat"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-wechat"></use></svg></a><a class="social-icon faa-parent animated-hover" href="/atom.xml" target="_blank" title="订阅-ATOM"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-rss"></use></svg></a><a class="social-icon faa-parent animated-hover" href="mailto:3067836615@qq.com" target="_blank" title="Email"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-youxiang-"></use></svg></a></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="anzhiyufont anzhiyu-icon-bars"></i><span>文章目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Bilibili%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98NodeJS"><span class="toc-number">1.</span> <span class="toc-text">Bilibili黑马程序员NodeJS</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFnodejs"><span class="toc-number">1.1.</span> <span class="toc-text">什么是nodejs</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A6%82%E4%BD%95%E8%BF%90%E8%A1%8Cjs%E4%BB%A3%E7%A0%81"><span class="toc-number">1.2.</span> <span class="toc-text">如何运行js代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97"><span class="toc-number">1.3.</span> <span class="toc-text">内置模块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="toc-number">1.4.</span> <span class="toc-text">模块化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#npm%E4%BD%BF%E7%94%A8"><span class="toc-number">1.5.</span> <span class="toc-text">npm使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#express"><span class="toc-number">1.6.</span> <span class="toc-text">express</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1"><span class="toc-number">1.6.1.</span> <span class="toc-text">路由</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%AD%E9%97%B4%E4%BB%B6"><span class="toc-number">1.6.2.</span> <span class="toc-text">中间件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%AD%E9%97%B4%E4%BB%B6%E7%9A%84%E5%88%86%E7%B1%BB"><span class="toc-number">1.6.3.</span> <span class="toc-text">中间件的分类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98"><span class="toc-number">1.7.</span> <span class="toc-text">跨域问题</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8cors%E7%AC%AC%E4%B8%89%E6%96%B9%E4%B8%AD%E9%97%B4%E4%BB%B6"><span class="toc-number">1.7.1.</span> <span class="toc-text">使用cors第三方中间件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mysql%E6%A8%A1%E5%9D%97"><span class="toc-number">1.8.</span> <span class="toc-text">mysql模块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Web%E5%BC%80%E5%8F%91%E6%A8%A1%E5%BC%8F"><span class="toc-number">1.9.</span> <span class="toc-text">Web开发模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9C%A8Express%E4%B8%AD%E4%BD%BF%E7%94%A8Session%E8%AE%A4%E8%AF%81"><span class="toc-number">1.10.</span> <span class="toc-text">在Express中使用Session认证</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JWT%E8%B7%A8%E5%9F%9F%E8%AE%A4%E8%AF%81"><span class="toc-number">1.11.</span> <span class="toc-text">JWT跨域认证</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9C%A8Express%E4%B8%AD%E4%BD%BF%E7%94%A8JWT"><span class="toc-number">1.12.</span> <span class="toc-text">在Express中使用JWT</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="anzhiyufont anzhiyu-icon-history"></i><span>最近发布</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/posts/98f3f974/" title="美化你的Github个人主页"><img src="https://image.insectmk.cn/hexo-gitee-blog/cover/github-insectmk.jpg" onerror='this.onerror=null,this.src="/static/img/website/404.jpg"' alt="美化你的Github个人主页"></a><div class="content"><a class="title" href="/posts/98f3f974/" title="美化你的Github个人主页">美化你的Github个人主页</a><time datetime="2024-07-30T02:52:23.000Z" title="发表于 2024-07-30 10:52:23">2024-07-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/10d64ca8/" title="我的Hexo博客多主题同时部署的实现思路（Butterfly+安知鱼）"><img src="https://image.insectmk.cn/hexo-gitee-blog/cover/hexo-butterfly.jpg" onerror='this.onerror=null,this.src="/static/img/website/404.jpg"' alt="我的Hexo博客多主题同时部署的实现思路（Butterfly+安知鱼）"></a><div class="content"><a class="title" href="/posts/10d64ca8/" title="我的Hexo博客多主题同时部署的实现思路（Butterfly+安知鱼）">我的Hexo博客多主题同时部署的实现思路（Butterfly+安知鱼）</a><time datetime="2024-07-30T01:30:07.000Z" title="发表于 2024-07-30 09:30:07">2024-07-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/129b7f4a/" title="使用Spring AI对接Ollama搭建自己的智能问答网站"><img src="https://image.insectmk.cn/hexo-gitee-blog/cover/ollama.jpg" onerror='this.onerror=null,this.src="/static/img/website/404.jpg"' alt="使用Spring AI对接Ollama搭建自己的智能问答网站"></a><div class="content"><a class="title" href="/posts/129b7f4a/" title="使用Spring AI对接Ollama搭建自己的智能问答网站">使用Spring AI对接Ollama搭建自己的智能问答网站</a><time datetime="2024-07-20T02:45:24.000Z" title="发表于 2024-07-20 10:45:24">2024-07-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/9c83ed78/" title="无需更改源码！让你的Hexo的文章在首页隐藏"><img src="https://image.insectmk.cn/hexo-gitee-blog/cover/hexo-hide-posts.jpg" onerror='this.onerror=null,this.src="/static/img/website/404.jpg"' alt="无需更改源码！让你的Hexo的文章在首页隐藏"></a><div class="content"><a class="title" href="/posts/9c83ed78/" title="无需更改源码！让你的Hexo的文章在首页隐藏">无需更改源码！让你的Hexo的文章在首页隐藏</a><time datetime="2024-07-19T02:22:45.000Z" title="发表于 2024-07-19 10:22:45">2024-07-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/posts/9348d5be/" title="使用Cloudflare加速Docker镜像下载"><img src="https://image.insectmk.cn/hexo-gitee-blog/cover/docker.png" onerror='this.onerror=null,this.src="/static/img/website/404.jpg"' alt="使用Cloudflare加速Docker镜像下载"></a><div class="content"><a class="title" href="/posts/9348d5be/" title="使用Cloudflare加速Docker镜像下载">使用Cloudflare加速Docker镜像下载</a><time datetime="2024-06-13T08:01:10.000Z" title="发表于 2024-06-13 16:01:10">2024-06-13</time></div></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div id="workboard"><div id="runtimeTextTip"></div></div><p id="ghbdages"><a class="github-badge" target="_blank" href="https://hexo.io/" style="margin-inline:5px" data-title="博客框架为Hexo_v7.3.0" title="博客框架为Hexo_v7.3.0"><img src="https://npm.elemecdn.com/anzhiyu-blog@2.1.5/img/badge/Frame-Hexo.svg" alt="博客框架为Hexo_v7.3.0"></a><a class="github-badge" target="_blank" href="https://blog.anheyu.com/" style="margin-inline:5px" data-title="本站使用AnZhiYu主题" title="本站使用AnZhiYu主题"><img src="https://npm.elemecdn.com/anzhiyu-theme-static@1.0.9/img/Theme-AnZhiYu-2E67D3.svg" alt="本站使用AnZhiYu主题"></a></p></div><div id="footer-bar"><div class="footer-bar-links"><div class="footer-bar-left"><div id="footer-bar-tips"><div class="copyright">&copy;2020 - 2024 By <a class="footer-bar-link" href="/" title="InsectMk" target="_blank">InsectMk</a></div></div><div id="footer-type-tips"></div></div><div class="footer-bar-right"><a class="footer-bar-link" target="_blank" rel="noopener" href="https://github.com/anzhiyu-c/hexo-theme-anzhiyu" title="主题">主题</a><a class="footer-bar-link" target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" title="蜀ICP备2023013851号-2">蜀ICP备2023013851号-2</a><a class="footer-bar-link" target="_blank" rel="noopener" href="https://beian.mps.gov.cn/#/query/webSearch?code=51142202000154" title="川公网安备51142202000154号">川公网安备51142202000154号</a></div></div></div></footer></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="sidebar-site-data site-data is-center"><a href="/archives/" title="archive"><div class="headline">文章</div><div class="length-num">121</div></a><a href="/tags/" title="tag"><div class="headline">标签</div><div class="length-num">117</div></a><a href="/categories/" title="category"><div class="headline">分类</div><div class="length-num">14</div></a></div><span class="sidebar-menu-item-title">功能</span><div class="sidebar-menu-item"><a class="darkmode_switchbutton menu-child" href="javascript:void(0);" title="显示模式"><i class="anzhiyufont anzhiyu-icon-circle-half-stroke"></i><span>显示模式</span></a></div><div class="back-menu-list-groups"><div class="back-menu-list-group"><div class="back-menu-list-title">网页</div><div class="back-menu-list"><a class="back-menu-item" target="_blank" rel="noopener" href="https://insectmk.cn/" title="主博客"><img class="back-menu-item-icon" src="/static/img/website/favicon.jpg" alt="主博客"><span class="back-menu-item-text">主博客</span></a><a class="back-menu-item" href="https://insectmk.top/" title="次博客"><img class="back-menu-item-icon" src="/static/img/website/favicon.jpg" alt="次博客"><span class="back-menu-item-text">次博客</span></a></div></div><div class="back-menu-list-group"><div class="back-menu-list-title">项目</div><div class="back-menu-list"><a class="back-menu-item" target="_blank" rel="noopener" href="https://gitee.com/insectmk/chatbot-web" title="智能聊天机器人网站"><img class="back-menu-item-icon" src="https://image.insectmk.cn/hexo-gitee-blog/project/icon/chatbot-web.jpg" alt="智能聊天机器人网站"><span class="back-menu-item-text">智能聊天机器人网站</span></a></div></div></div><div class="menus_items"><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-home"></use></svg><span>主页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-hand-peace"></use></svg><span>娱乐</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/entertainment/gallery/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-images"></use></svg><span>图库</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-comments"></use></svg><span>交流</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/contact/comments/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-paper-plane"></use></svg><span>留言板</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/contact/link/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-link"></use></svg><span>友链</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-compass"></use></svg><span>目录</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/categories/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-archive"></use></svg><span>分类</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/tags/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-tags"></use></svg><span>标签</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/archives/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-folder-open"></use></svg><span>归档</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-server"></use></svg><span>服务</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/server/left4dead2/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-icons-left__dead_"></use></svg><span>求生之路</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/server/minecraft/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-minecraft"></use></svg><span>我的世界</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-clipboard"></use></svg><span>日志</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/log/website/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-website-with-different-sections"></use></svg><span>个人网站</span></a></li><li><a class="site-page child faa-parent animated-hover" href="/log/pc/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-desktop"></use></svg><span>个人电脑</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-bars"></use></svg><span>其他</span></a><ul class="menus_item_child"><li><a class="site-page child faa-parent animated-hover" href="/extend/remind/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-note"></use></svg><span>备忘</span></a></li></ul></div><div class="menus_item"><a class="site-page faa-parent animated-hover" href="/about/"><svg class="icon faa-tada" aria-hidden="true"><use xlink:href="#icon-id-card"></use></svg><span>关于</span></a></div></div><span class="sidebar-menu-item-title">标签</span><div class="card-tags"><div class="item-headline"></div><div class="card-tag-cloud"><a href="/tags/AOP/" style="font-size:.88rem">AOP<sup>1</sup></a><a href="/tags/Butterfly/" style="font-size:.88rem">Butterfly<sup>4</sup></a><a href="/tags/Docker/" style="font-size:.88rem">Docker<sup>6</sup></a><a href="/tags/ElementUI/" style="font-size:.88rem">ElementUI<sup>1</sup></a><a href="/tags/Frp/" style="font-size:.88rem">Frp<sup>1</sup></a><a href="/tags/Hexo/" style="font-size:.88rem;font-weight:500;color:var(--anzhiyu-lighttext)">Hexo<sup>8</sup></a><a href="/tags/IntelliJ-IDEA/" style="font-size:.88rem">IntelliJ IDEA<sup>1</sup></a><a href="/tags/JDK/" style="font-size:.88rem">JDK<sup>1</sup></a><a href="/tags/JWT/" style="font-size:.88rem">JWT<sup>1</sup></a><a href="/tags/Java/" style="font-size:.88rem">Java<sup>35</sup></a><a href="/tags/Junit/" style="font-size:.88rem">Junit<sup>1</sup></a><a href="/tags/Leanote/" style="font-size:.88rem">Leanote<sup>1</sup></a><a href="/tags/Maven/" style="font-size:.88rem">Maven<sup>2</sup></a><a href="/tags/MyBatisPlus/" style="font-size:.88rem">MyBatisPlus<sup>1</sup></a><a href="/tags/MySQL5-7/" style="font-size:.88rem">MySQL5.7<sup>1</sup></a><a href="/tags/Mybatis/" style="font-size:.88rem">Mybatis<sup>1</sup></a><a href="/tags/MybatisPlus/" style="font-size:.88rem">MybatisPlus<sup>1</sup></a><a href="/tags/OSS/" style="font-size:.88rem">OSS<sup>1</sup></a><a href="/tags/Spring/" style="font-size:.88rem">Spring<sup>2</sup></a><a href="/tags/Spring-Boot/" style="font-size:.88rem">SpringBoot<sup>6</sup></a><a href="/tags/Vue2/" style="font-size:.88rem">Vue2<sup>9</sup></a><a href="/tags/Vue3/" style="font-size:.88rem">Vue3<sup>1</sup></a><a href="/tags/Vuetify/" style="font-size:.88rem">Vuetify<sup>1</sup></a><a href="/tags/Vuex/" style="font-size:.88rem">Vuex<sup>1</sup></a><a href="/tags/Waline/" style="font-size:.88rem">Waline<sup>3</sup></a><a href="/tags/mvc/" style="font-size:.88rem">mvc<sup>3</sup></a><a href="/tags/mybatis/" style="font-size:.88rem">mybatis<sup>1</sup></a><a href="/tags/profile/" style="font-size:.88rem">profile<sup>1</sup></a><a href="/tags/spring/" style="font-size:.88rem">spring<sup>5</sup></a><a href="/tags/springboot/" style="font-size:.88rem">springboot<sup>4</sup></a><a href="/tags/transaction/" style="font-size:.88rem">transaction<sup>1</sup></a><a href="/tags/yaml/" style="font-size:.88rem">yaml<sup>2</sup></a><a href="/tags/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2/" style="font-size:.88rem">个人博客<sup>11</sup></a><a href="/tags/%E4%BA%8B%E5%8A%A1/" style="font-size:.88rem">事务<sup>1</sup></a><a href="/tags/%E5%88%86%E9%A1%B5/" style="font-size:.88rem">分页<sup>1</sup></a><a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size:.88rem;font-weight:500;color:var(--anzhiyu-lighttext)">前端<sup>1</sup></a><a href="/tags/%E6%9C%8D%E5%8A%A1%E5%99%A8/" style="font-size:.88rem">服务器<sup>20</sup></a><a href="/tags/%E6%AF%95%E4%B8%9A%E8%AE%BE%E8%AE%A1/" style="font-size:.88rem">毕业设计<sup>14</sup></a><a href="/tags/%E7%A6%85%E9%81%93/" style="font-size:.88rem">禅道<sup>1</sup></a><a href="/tags/%E7%BB%BF%E8%89%B2%E8%A7%A3%E5%8E%8B/" style="font-size:.88rem">绿色解压<sup>1</sup></a></div></div><hr></div></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="anzhiyufont anzhiyu-icon-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="anzhiyufont anzhiyu-icon-circle-half-stroke"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="anzhiyufont anzhiyu-icon-arrows-left-right"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="anzhiyufont anzhiyu-icon-gear"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="anzhiyufont anzhiyu-icon-list-ul"></i></button><button id="chat-btn" type="button" title="聊天"><i class="anzhiyufont anzhiyu-icon-comment-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="anzhiyufont anzhiyu-icon-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="anzhiyufont anzhiyu-icon-arrow-up"></i></button></div></div><div id="nav-music"><a id="nav-music-hoverTips" onclick="anzhiyu.musicToggle()" accesskey="m">播放音乐</a><div id="console-music-bg"></div><meting-js id="975968032" server="netease" type="playlist" mutex="true" preload="none" theme="var(--anzhiyu-main)" data-lrctype="0" order="random" volume="0.7"></meting-js></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="anzhiyufont anzhiyu-icon-xmark"></i></button></nav><div class="is-center" id="loading-database"><i class="anzhiyufont anzhiyu-icon-spinner anzhiyu-pulse-icon"></i><span> 数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"></div></div><hr><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="anzhiyufont anzhiyu-icon-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="anzhiyufont anzhiyu-icon-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="anzhiyufont anzhiyu-icon-arrow-rotate-right" style="font-size:1rem"></i></div><div class="rightMenu-item" id="menu-top"><i class="anzhiyufont anzhiyu-icon-arrow-up"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuPlugin"><div class="rightMenu-item" id="menu-copytext"><i class="anzhiyufont anzhiyu-icon-copy"></i><span>复制选中文本</span></div><div class="rightMenu-item" id="menu-pastetext"><i class="anzhiyufont anzhiyu-icon-paste"></i><span>粘贴文本</span></div><a class="rightMenu-item" id="menu-commenttext"><i class="anzhiyufont anzhiyu-icon-comment-medical"></i><span>引用到评论</span></a><div class="rightMenu-item" id="menu-newwindow"><i class="anzhiyufont anzhiyu-icon-window-restore"></i><span>新窗口打开</span></div><div class="rightMenu-item" id="menu-copylink"><i class="anzhiyufont anzhiyu-icon-link"></i><span>复制链接地址</span></div><div class="rightMenu-item" id="menu-copyimg"><i class="anzhiyufont anzhiyu-icon-images"></i><span>复制此图片</span></div><div class="rightMenu-item" id="menu-downloadimg"><i class="anzhiyufont anzhiyu-icon-download"></i><span>下载此图片</span></div><div class="rightMenu-item" id="menu-newwindowimg"><i class="anzhiyufont anzhiyu-icon-window-restore"></i><span>新窗口打开图片</span></div><div class="rightMenu-item" id="menu-search"><i class="anzhiyufont anzhiyu-icon-magnifying-glass"></i><span>站内搜索</span></div><div class="rightMenu-item" id="menu-searchBaidu"><i class="anzhiyufont anzhiyu-icon-magnifying-glass"></i><span>百度搜索</span></div><div class="rightMenu-item" id="menu-music-toggle"><i class="anzhiyufont anzhiyu-icon-play"></i><span>播放音乐</span></div><div class="rightMenu-item" id="menu-music-back"><i class="anzhiyufont anzhiyu-icon-backward"></i><span>切换到上一首</span></div><div class="rightMenu-item" id="menu-music-forward"><i class="anzhiyufont anzhiyu-icon-forward"></i><span>切换到下一首</span></div><div class="rightMenu-item" id="menu-music-playlist" onclick="window.open(&quot;https://y.qq.com/n/ryqq/playlist/8802438608&quot;, &quot;_blank&quot;);" style="display:none"><i class="anzhiyufont anzhiyu-icon-radio"></i><span>查看所有歌曲</span></div><div class="rightMenu-item" id="menu-music-copyMusicName"><i class="anzhiyufont anzhiyu-icon-copy"></i><span>复制歌名</span></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" id="menu-randomPost"><i class="anzhiyufont anzhiyu-icon-shuffle"></i><span>随便逛逛</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="anzhiyufont anzhiyu-icon-cube"></i><span>博客分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="anzhiyufont anzhiyu-icon-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item" id="menu-copy" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-copy"></i><span>复制地址</span></a><a class="rightMenu-item" id="menu-commentBarrage" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-message"></i><span class="menu-commentBarrage-text">关闭热评</span></a><a class="rightMenu-item" id="menu-darkmode" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-circle-half-stroke"></i><span class="menu-darkmode-text">深色模式</span></a><a class="rightMenu-item" id="menu-translate" href="javascript:void(0);"><i class="anzhiyufont anzhiyu-icon-language"></i><span>轉為繁體</span></a></div></div><div id="rightmenu-mask"></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.cbd.int/@fancyapps/ui@5.0.28/dist/fancybox/fancybox.umd.js"></script><script src="https://cdn.cbd.int/instant.page@5.2.0/instantpage.js" type="module"></script><script src="https://cdn.cbd.int/node-snackbar@0.1.16/dist/snackbar.min.js"></script><canvas id="universe"></canvas><script async src="https://npm.elemecdn.com/anzhiyu-theme-static@1.0.0/dark/dark.js"></script><script>var HoldLog=console.log;console.log=function(){};let now1=new Date;queueMicrotask(()=>{function o(){HoldLog.apply(console,arguments)}var c=new Date("04/11/2022 14:03:44"),c=(now1.setTime(now1.getTime()+250),(now1-c)/1e3/60/60/24),c=["欢迎使用安知鱼!","生活明朗, 万物可爱",`
        
       █████╗ ███╗   ██╗███████╗██╗  ██╗██╗██╗   ██╗██╗   ██╗
      ██╔══██╗████╗  ██║╚══███╔╝██║  ██║██║╚██╗ ██╔╝██║   ██║
      ███████║██╔██╗ ██║  ███╔╝ ███████║██║ ╚████╔╝ ██║   ██║
      ██╔══██║██║╚██╗██║ ███╔╝  ██╔══██║██║  ╚██╔╝  ██║   ██║
      ██║  ██║██║ ╚████║███████╗██║  ██║██║   ██║   ╚██████╔╝
      ╚═╝  ╚═╝╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝╚═╝   ╚═╝    ╚═════╝
        
        `,"已上线",Math.floor(c),"天","©2020 By 安知鱼 V1.6.12"],e=["NCC2-036","调用前置摄像头拍照成功，识别为【小笨蛋】.","Photo captured: ","🤪"];setTimeout(o.bind(console,`
%c${c[0]} %c ${c[1]} %c ${c[2]} %c${c[3]}%c ${c[4]}%c ${c[5]}

%c ${c[6]}
`,"color:#425AEF","","color:#425AEF","color:#425AEF","","color:#425AEF","")),setTimeout(o.bind(console,`%c ${e[0]} %c ${e[1]} %c 
${e[2]} %c
${e[3]}
`,"color:white; background-color:#4fd953","","",'background:url("https://npm.elemecdn.com/anzhiyu-blog@1.1.6/img/post/common/tinggge.gif") no-repeat;font-size:450%')),setTimeout(o.bind(console,"%c WELCOME %c 你好，小笨蛋.","color:white; background-color:#4f90d9","")),setTimeout(console.warn.bind(console,"%c ⚡ Powered by 安知鱼 %c 你正在访问 InsectMk 的博客.","color:white; background-color:#f0ad4e","")),setTimeout(o.bind(console,"%c W23-12 %c 你已打开控制台.","color:white; background-color:#4f90d9","")),setTimeout(console.warn.bind(console,"%c S013-782 %c 你现在正处于监控中.","color:white; background-color:#d9534f",""))})</script><script async src="/anzhiyu/random.js"></script><script async>!function(){var n,r,o,a,i,e=new Date("04/11/2022 14:03:44"),l=new Date;setInterval(()=>{var t;if(l=new Date,i=l.getHours(),t=(l-e)/1e3/60/60/24,n=Math.floor(t),t=(l-e)/1e3/60/60-24*n,r=Math.floor(t),1==String(r).length&&(r="0"+r),t=(l-e)/1e3/60-1440*n-60*r,o=Math.floor(t),1==String(o).length&&(o="0"+o),t=(l-e)/1e3-86400*n-3600*r-60*o,a=Math.round(t),1==String(a).length&&(a="0"+a),document.getElementById("footer")){let e="";e=(i<18&&9<=i||null!=(t=document.querySelector("#workboard .workSituationImg"))&&(t.src="",t.title="",t.alt=""),`本站居然运行了 ${n} 天<span id='runtime'> ${r} 小时 ${o} 分 ${a} 秒 </span><i class='anzhiyufont anzhiyu-icon-heartbeat' style='color:red'></i>`),document.getElementById("runtimeTextTip")&&(document.getElementById("runtimeTextTip").innerHTML=e)}},1e3)}()</script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>(()=>{let e=()=>{Waline.init(Object.assign({el:"#waline-wrap",serverURL:"https://waline-server.insectmk.cn/",pageview:!0,dark:'html[data-theme="dark"]',path:window.location.pathname,comment:!0},{reaction:["/static/img/waline/tieba_agree.png","/static/img/waline/tieba_look_down.png","/static/img/waline/tieba_sunglasses.png","/static/img/waline/tieba_pick_nose.png","/static/img/waline/tieba_awkward.png","/static/img/waline/tieba_sleep.png"],requiredMeta:["nick","mail"],locale:{placeholder:"欢迎评论哟~"}}))};var i=async()=>{"object"==typeof Waline||(await getCSS("https://cdn.cbd.int/@waline/client@2.15.5/dist/waline.css"),await getScript("https://cdn.cbd.int/@waline/client@2.15.5/dist/waline.js")),e()};setTimeout(i,0)})()</script><input type="hidden" name="page-type" id="page-type" value="post"></div><script>window.addEventListener("load",()=>{let t=e=>e=""!==e&&150<(e=(e=(e=(e=e.replace(/<img.*?src="(.*?)"?[^\>]+>/gi,"[图片]")).replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi,"[链接]")).replace(/<pre><code>.*?<\/pre>/gi,"[代码]")).replace(/<[^>]+>/g,"")).length?e.substring(0,150)+"...":e,a=t=>{let a="";if(t.length)for(let e=0;e<t.length;e++)a=(a=(a+="<div class='aside-list-item'>")+`<a href='${t[e].url}' class='thumbnail'><img src='${t[e].avatar}' alt='${t[e].nick}'></a>`)+`<div class='content'>
        <a class='comment' href='${t[e].url}' title='${t[e].content}'>${t[e].content}</a>
        <div class='name'><span>${t[e].nick} / </span><time datetime="${t[e].date}">${anzhiyu.diffDate(t[e].date,!0)}</time></div>
        </div></div>`;else a+="没有评论";var e=document.querySelector("#card-newest-comments .aside-list");e&&(e.innerHTML=a),window.lazyLoadInstance&&window.lazyLoadInstance.update(),window.pjax&&window.pjax.refresh(e)};var e=()=>{var e;document.querySelector("#card-newest-comments .aside-list")&&((e=saveToLocal.get("waline-newest-comments"))?a(JSON.parse(e)):(async()=>{try{var e=(await(await fetch("https://waline-server.insectmk.cn/api/comment?type=recent&count=6",{method:"GET"})).json()).data.map(e=>({content:t(e.comment),avatar:e.avatar,nick:e.nick,url:e.url+"#"+e.objectId,date:e.time||e.insertedAt}));saveToLocal.set("waline-newest-comments",JSON.stringify(e),10/1440),a(e)}catch(e){console.error(e),document.querySelector("#card-newest-comments .aside-list").textContent="无法获取评论，请确认相关配置是否正确"}})())};e(),document.addEventListener("pjax:complete",e)})</script><script>var visitorMail=""</script><script async data-pjax src="https://cdn.cbd.int/anzhiyu-theme-static@1.0.0/waterfall/waterfall.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/qrcodejs/1.0.0/qrcode.min.js"></script><link rel="stylesheet" href="https://cdn.cbd.int/anzhiyu-theme-static@1.1.9/icon/ali_iconfont_css.css"><script async src="//at.alicdn.com/t/c/font_3795172_6hp27xdg2x7.js"></script><script>(()=>{var a,t,h,e;window.ChatraSetup={startHidden:!0},window.chatBtnFn=()=>{document.getElementById("chatra").classList.contains("chatra--expanded")?(Chatra("minimizeWidget"),Chatra("hide")):(Chatra("openChat",!0),Chatra("show"))};a=document,t=window,h="Chatra",t.ChatraID="SjkKhfiLMpdfaPPhc",e=a.createElement("script"),t[h]=t[h]||function(){(t[h].q=t[h].q||[]).push(arguments)},e.async=!0,e.src="https://call.chatra.io/chatra.js",a.head&&a.head.appendChild(e)})()</script><link rel="stylesheet" href="https://cdn.cbd.int/anzhiyu-theme-static@1.0.0/aplayer/APlayer.min.css" media="print" onload='this.media="all"'><script src="https://cdn.cbd.int/anzhiyu-blog-static@1.0.1/js/APlayer.min.js"></script><script src="https://cdn.cbd.int/hexo-anzhiyu-music@1.0.1/assets/js/Meting2.min.js"></script><script src="https://cdn.cbd.int/pjax@0.2.8/pjax.min.js"></script><script>let pjaxSelectors=["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"];var pjax=new Pjax({elements:'a:not([target="_blank"])',selectors:pjaxSelectors,cacheBust:!1,analytics:!1,scrollRestoration:!1});document.addEventListener("pjax:send",function(){if(anzhiyu.removeGlobalFnEvent("pjax"),anzhiyu.removeGlobalFnEvent("themeChange"),document.getElementById("rightside").classList.remove("rightside-show"),window.aplayers)for(let e=0;e<window.aplayers.length;e++)window.aplayers[e].options.fixed||window.aplayers[e].destroy();"object"==typeof typed&&typed.destroy();var e=document.body.classList;e.contains("read-mode")&&e.remove("read-mode")}),document.addEventListener("pjax:complete",function(){window.refreshFn(),document.querySelectorAll("script[data-pjax]").forEach(e=>{let t=document.createElement("script");var a=e.text||e.textContent||e.innerHTML||"";Array.from(e.attributes).forEach(e=>t.setAttribute(e.name,e.value)),t.appendChild(document.createTextNode(a)),e.parentNode.replaceChild(t,e)}),GLOBAL_CONFIG.islazyload&&window.lazyLoadInstance.update(),"function"==typeof panguInit&&panguInit(),"function"==typeof gtag&&gtag("config","",{page_path:window.location.pathname}),"object"==typeof _hmt&&_hmt.push(["_trackPageview",window.location.pathname]),"function"==typeof loadMeting&&document.getElementsByClassName("aplayer").length&&loadMeting(),"object"==typeof Prism&&Prism.highlightAll()}),document.addEventListener("pjax:error",e=>{404===e.request.status&&pjax.loadUrl("/404")})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script charset="UTF-8" src="https://cdn.cbd.int/anzhiyu-theme-static@1.1.5/accesskey/accesskey.js"></script></div><div id="popup-window"><div class="popup-window-title">通知</div><div class="popup-window-divider"></div><div class="popup-window-content"><div class="popup-tip">你好呀</div><div class="popup-link"><i class="anzhiyufont anzhiyu-icon-arrow-circle-right"></i></div></div></div></body></html>